package com.test.jni.service;

import com.sun.jna.Native;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Jna调用服务
 * 因为需要加载文件，所用用注入方式，只加载一次
 */
@Slf4j
@Service
public class CallJnaService {

    private static LibraryStruct LIBRARY_STRUCT;

    static {

        // Windows环境下,生成dll命令： gcc -shared -o libhello.dll hello.c
        String libhelloPath = CallJnaService.class.getResource("/").getPath() + "native/libhello.dll";
        libhelloPath = libhelloPath.substring(1);
        // 以上只是win idea 需要跑通用了 dll
        // 注意：linux 环境需要换成这个
        // 获取so路径的地址
        // String libhelloPath = CallJnaService.class.getResource("/").getPath() + "native/libhello.so";

        // 加载动态链接库
        log.info("libhelloPath = {}", libhelloPath);
        LIBRARY_STRUCT = Native.load(libhelloPath, LibraryStruct.class);
    }

    public void callJnaMethod() {

        LibraryStruct.StudentStruct.ByValue stuByValue = new LibraryStruct.StudentStruct.ByValue();
        LibraryStruct.TeacherStruct.ByReference teaByReference = new LibraryStruct.TeacherStruct.ByReference();

        stuByValue.stu_age = 18;
        stuByValue.stu_name = "小学生";

        teaByReference.tea_age = 48;
        teaByReference.tea_name = "高级教师";

        // 调用函数之前
        log.info("调用函数之前teaByReference：{}", teaByReference.toString());
        // 调用方法。返回结果
        LibraryStruct.TeacherStruct.ByValue result = LIBRARY_STRUCT.stuTea(stuByValue, teaByReference);
        // 查看传地址的teaByReference的值是否变更
        log.info("调用函数之后teaByReference：{}", teaByReference.toString());
        // 函数返回结果
        log.info("调用函数返回结果result.name：{}", result.toString());
    }

}